package cn.net.shuxing.yifu.common.front.controller;

import cn.net.shuxing.yifu.common.bean.UserRealInfo;
import cn.net.shuxing.yifu.common.constant.CodeConst;
import cn.net.shuxing.yifu.common.constant.OssConstant;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.service.OssCommonService;
import cn.net.shuxing.yifu.common.service.UserBankCardService;
import cn.net.shuxing.yifu.common.service.UserRealInfoService;
import cn.net.shuxing.yifu.common.util.FileUtil;
import cn.net.shuxing.yifu.common.util.UrlUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.UUID;

@Api("模块控制器")
@RestController
@RequestMapping("/front/safe")
public class SafeController {
    @Autowired
    protected UserRealInfoService userRealInfoService;

    @Autowired
    protected UserBankCardService userBankCardService;

    @Autowired
    protected ServletContext servletContext;

    @Autowired
    protected OssCommonService ossCommonService;

    @ApiOperation("真实信息实名认证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "cardTypeId", value = "证件类型id", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "realName", value = "真实姓名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "idCardNum", value = "证件号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "idCardFrontPhoto", value = "证件正面照(人脸)", required = true, dataType = "file", paramType = "query"),
            @ApiImplicitParam(name = "idCardBackPhoto", value = "证件背面照(国徽)", required = true, dataType = "file", paramType = "query"),
            @ApiImplicitParam(name = "takingCardPhoto", value = "手持证件照", required = true, dataType = "file", paramType = "query"),

    })
    @RequestMapping("/realinfo/verify")
    public BaseDto uploadRealInfo(Integer userId, Integer cardTypeId, String realName, String idCardNum,
                                  @RequestParam("idCardFrontPhoto") String idCardFrontPhoto,
                                  @RequestParam("idCardBackPhoto") String idCardBackPhoto,
                                  @RequestParam("takingCardPhoto") String takingCardPhoto) throws UnsupportedEncodingException {
        System.out.println("uploadRealInfo 实名认证真实名称：" + realName);
//        /** 身份实名认证 **/
//        UserRealInfo userRealInfo = new UserRealInfo();
//        userRealInfo.setCardTypeId(cardTypeId);
//        userRealInfo.setIdCardNum(idCardNum);
//        userRealInfo.setRealName(realName);
//
//        boolean insertable = userRealInfoService.insertable(idCardNum);
//        if (!insertable) {
//            return BaseDto.error("此身份证已被认证");
//        }
//
//        boolean identifyVerify = userRealInfoService.verify(idCardNum, realName);
//
//        /** 身份认证未通过 **/
//        if (!identifyVerify) {
//            BaseDto baseDto = new BaseDto();
//            baseDto.setCode(CodeConst.ERROR);
//            baseDto.setMsg("身份证号和姓名不符,认证失败");
//            return baseDto;
//        } else {
//            userRealInfo = userRealInfoService.getByPrimaryKey(userId);
//            if (userRealInfo == null) {
//                userRealInfo = new UserRealInfo();
//                userRealInfo.setId(userId);
//                userRealInfo.setRealName(realName);
//                userRealInfo.setIdCardNum(idCardNum);
//                userRealInfoService.insert(userRealInfo);
//            } else {
//                userRealInfo.setId(userId);
//                userRealInfo.setRealName(realName);
//                userRealInfo.setIdCardNum(idCardNum);
//                userRealInfoService.update(userRealInfo);
//            }
//        }
//
//        /** 验证身份证照片 **/
//        userRealInfo = userRealInfoService.getByPrimaryKey(userId);
//        try {
//            /** 验证正面照 **/
//            String filename = idCardBackPhoto.getOriginalFilename();
//            String suffix = filename.substring(filename.lastIndexOf("."));
//            Long sizeL = idCardBackPhoto.getSize();
//            int size = sizeL.intValue();
//            BaseDto baseDto = userRealInfoService.verifyIdCardPhoto(idCardFrontPhoto.getInputStream(), suffix, size, true, userRealInfo);
//            if (baseDto.getCode() == CodeConst.ERROR) {
//                return baseDto;
//            }
//
//            /** 验证背面照 **/
//            filename = idCardBackPhoto.getOriginalFilename();
//            suffix = filename.substring(filename.lastIndexOf("."));
//            sizeL = idCardBackPhoto.getSize();
//            size = sizeL.intValue();
//            baseDto = userRealInfoService.verifyIdCardPhoto(idCardBackPhoto.getInputStream(), suffix, size, true, userRealInfo);
//            if (baseDto.getCode() == CodeConst.ERROR) {
//                return baseDto;
//            }
//
//            /** 上传手持身份证照 **/
//            filename = takingCardPhoto.getOriginalFilename();
//            suffix = filename.substring(filename.lastIndexOf("."));
//            sizeL = idCardBackPhoto.getSize();
//            size = sizeL.intValue();
//            byte[] content = new byte[size];
//            takingCardPhoto.getInputStream().read(content);
//            baseDto = userRealInfoService.uploadTakingCardPhoto(content, suffix, userId);
//            if (baseDto.getCode() == CodeConst.ERROR) {
//                return baseDto;
//            }
//            baseDto = new BaseDto();
//            baseDto.setData("验证通过");
//            return baseDto;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        BaseDto baseDto = new BaseDto();
//        baseDto.setCode(CodeConst.ERROR);
//        baseDto.setMsg("未知错误");
//        return baseDto;
        return BaseDto.ok(uploadRealInfoBase64(userId, cardTypeId, realName, idCardNum, idCardFrontPhoto, idCardBackPhoto, takingCardPhoto));
    }

    @RequestMapping("/realinfo/verify/upload")
    public BaseDto uploadPhoto(@RequestParam("file") MultipartFile file) throws IOException {
        String objectName = "idCardPhoto-" + UUID.randomUUID().toString().substring(0, 10);
        File file1 = new File(new File("").getAbsolutePath() + File.separator + objectName);
        if (file1.exists())
            file1.delete();
        file1.createNewFile();
        file.transferTo(file1);
        String bucketName = OssConstant.ossBucketName;
        ossCommonService.uploadFile(bucketName, objectName, file1);
        if (file1.exists())
            file1.delete();
        return BaseDto.ok(objectName);
    }

    @RequestMapping("/realinfo/verify/base64")
    public BaseDto uploadRealInfoBase64(Integer userId, Integer cardTypeId, String realName, String idCardNum,
                                        @RequestParam("idCardFrontPhoto") String idCardFrontPhoto,
                                        @RequestParam("idCardBackPhoto") String idCardBackPhoto,
                                        @RequestParam("takingCardPhoto") String takingCardPhoto) throws UnsupportedEncodingException {
//        realName = UrlUtil.getURLEncoderString(realName);
        realName = URLDecoder.decode(realName);
//        return BaseDto.ok("");
        boolean realNameVerify = false;
        realNameVerify = userRealInfoService.verify(idCardNum, realName);
        String suffix = ".jpg";
        /** 身份认证未通过 **/
        if (!realNameVerify) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("身份证号和姓名不符,认证失败");
            return baseDto;
        }

        UserRealInfo userRealInfo = userRealInfoService.getByPrimaryKey(userId);
        if (userRealInfo == null) {
            boolean insertable = userRealInfoService.insertable(idCardNum);
            if (insertable) {
                if (userRealInfo == null) {
                    userRealInfo = new UserRealInfo();
                    userRealInfo.setId(userId);
                    userRealInfo.setRealName(realName);
                    userRealInfo.setIdCardNum(idCardNum);
                    userRealInfo.setVerified(0);
                    userRealInfo.setCardTypeId(cardTypeId);
                    userRealInfoService.insert(userRealInfo);
                }
            } else {

                return BaseDto.error("此身份证已被认证");
            }
        } else {
            if (userRealInfo.getVerified() == 1) {
                return BaseDto.error("已通过实名认证");
            }
            if (userRealInfo.getVerified() == 0) {
                return BaseDto.error("审核中");
            }
            if (userRealInfo.getVerified() == 2) {
                boolean insertable = userRealInfoService.insertable(idCardNum);
                if (insertable) {
                    userRealInfo.setRealName(realName);
                    userRealInfo.setIdCardNum(idCardNum);
                    userRealInfo.setVerified(0);
                    userRealInfo.setCardTypeId(cardTypeId);
                    userRealInfoService.update(userRealInfo);
                } else {
                    if (userRealInfo.getIdCardNum().equals(idCardNum) == false) {
                        return BaseDto.error("此身份证已被注册");
                    } else {
                        userRealInfo.setRealName(realName);
                        userRealInfo.setIdCardNum(idCardNum);
                        userRealInfo.setVerified(0);
                        userRealInfo.setCardTypeId(cardTypeId);
                        userRealInfoService.update(userRealInfo);
                    }
                }
            }
        }


        /** 验证身份证照片 **/


        String bucketName = OssConstant.ossBucketName;


        userRealInfo.setIdCardFrontPhoto(idCardFrontPhoto);
        userRealInfo.setIdCardBackPhoto(idCardBackPhoto);
        userRealInfo.setTakingCardPhoto(takingCardPhoto);
        userRealInfo.setVerified(0);
        userRealInfoService.update(userRealInfo);

        BaseDto baseDto = new BaseDto();
        baseDto.setData("审核中");
        return baseDto;

//        BaseDto baseDto = new BaseDto();
//        baseDto.setCode(CodeConst.ERROR);
//        baseDto.setMsg("未知错误");
//        return baseDto;
    }

}
